<template>
    <app-layout>
        <view :style="{paddingBottom: `calc(${botNavHei}rpx + env(safe-area-inset-bottom))`}">
            <view v-if="video_url" class="dialog dir-top-nowrap main-center cross-center" @click="video_url = ''">
                <video :src="video_url" autoplay style="width: 100%;" @click.stop=""></video>
            </view>
            <view v-for="(item,index) in formList" :key="index">
                <template v-if="item.id === 'image-text'">
                    <view :style="{backgroundColor: item.data.bg || 'inherit'}" style="padding: 0 24rpx;">
                        <app-rich :content='item.data.content'></app-rich>
                    </view>
                </template>
                <template v-else-if="item.id === 'link'">
                    <app-associated-link
                        :arrows-switch="item.data.arrowsSwitch"
                        :background="item.data.background"
                        :color="item.data.color"
                        :font-size="item.data.fontSize"
                        :link="item.data.link"
                        :pic-switch="item.data.picSwitch"
                        :pic-url="item.data.picUrl"
                        :position="item.data.position"
                        :style-color="item.data.styleColor"
                        :styleNum="item.data.style"
                        :title="item.data.title"
                    ></app-associated-link>
                </template>

                <template v-else-if="item.id === 'rubik'">
                    <view style="position: relative">
                        <app-image-ad
                            :height="item.data.height"
                            :image-style="item.data.style"
                            :list="item.data.list"
                        ></app-image-ad>
                        <block v-for="(hotspot, hotspot_index) in item.data.hotspot" :key="hotspot_index">
                            <app-hotspot v-bind:hotspot="rubikHotspot(hotspot)"></app-hotspot>
                        </block>
                    </view>
                </template>
                <template v-else-if="item.id === 'empty'">
                    <app-empty
                        :background-color="item.data.background"
                        :height="item.data.height"
                    ></app-empty>
                </template>
                <view v-else-if="item.id === 'uimage'" v-show="componentShow(item)">
                    <diy-form-uimage :index="index"
                                     :value="item.data"
                                     @updateValue="updateValue"></diy-form-uimage>
                </view>
                <view v-else-if="item.id === 'uvideo'" v-show="componentShow(item)">
                    <diy-form-uvideo :index="index"
                                     :value="item.data"
                                     @show="play"
                                     @updateValue="updateValue"></diy-form-uvideo>
                </view>
                <view v-else-if="item.id === 'menu'" v-show="componentShow(item)"><diy-form-menu :index="index"
                               :value="item.data"
                               @updateValue="updateValue"></diy-form-menu></view>
                <view v-else-if="item.id === 'calendar'" v-show="componentShow(item)"><diy-form-calendar :index="index"
                                   :value="item.data"
                                   @updateValue="updateValue"></diy-form-calendar></view>
                <view v-else-if="item.id === 'switch'" v-show="componentShow(item)"><diy-form-switch :index="index"
                                 :value="item.data"
                                 @updateValue="updateValue"></diy-form-switch></view>
                <view v-else-if="item.id === 'agreement'" v-show="componentShow(item)" ><diy-form-agreement :index="index"
                                    :value="item.data"
                                    @updateValue="updateValue"></diy-form-agreement></view>
                <view v-else-if="item.id === 'radio'" v-show="componentShow(item)">
                    <diy-form-radio :index="index"
                                    :new-list="radioValue(item)"
                                    :ref="'refradio' + item.data.key"
                                    :key="index"
                                    :value="item.data"
                                    @updateValue="updateValue"></diy-form-radio>
                </view>
                <view v-else-if="item.id === 'select'" v-show="componentShow(item)">
                    <diy-form-radio  :index="index"
                                    :new-list="selectValue(item.data.key)"
                                    :value="item.data"
                                    :ref="'refselect' + item.data.key"
                                    mode="select"
                                     :key="index"
                                    @updateValue="updateValue"></diy-form-radio>
                </view>
                <view  v-else-if="item.id === 'input'" v-show="componentShow(item)"><diy-form-input :index="index"
                                :value="item.data"
                                @updateValue="updateValue"></diy-form-input></view>
                <view  v-else-if="item.id === 'text'" v-show="componentShow(item)"><diy-form-input :index="index"
                                :value="item.data"
                                mode="text"
                                @updateValue="updateValue"></diy-form-input></view>
                <view v-else-if="item.id === 'position'" v-show="componentShow(item)"><diy-form-input :index="index"
                                :value="item.data"
                                mode="position"
                                @updateValue="updateValue"></diy-form-input></view>
                <view v-else-if="item.id == 'calc'" v-show="componentShow(item)"><diy-calc :index="index"
                          :other-form="otherForm"
                          :value="item.data"
                          @updateValue="updateValue"></diy-calc></view>
                <view v-else-if="item.id == 'number-in'" v-show="componentShow(item)"><diy-number-in  :index="index"
                               :value="item.data"
                               @updateValue="updateValue"></diy-number-in></view>
                <view v-else-if="item.id === 'form-goods-button'" v-show="componentShow(item)"><diy-form-button
                                 :value="item.data"
                                 @click="reset"></diy-form-button></view>
            </view>
        </view>
    </app-layout>
</template>

<script>


import appRich from "../../components/basic-component/app-rich/parse";
import appEmpty from "../../components/basic-component/app-empty/app-empty";
import appImageAd from "../../components/page-component/app-image-ad/app-image-ad";
import appHotspot from "../../components/basic-component/app-hotspot/app-hotspot";
import appVideo from "../../components/page-component/app-video/app-video";
import appCopyright from "../../components/page-component/app-copyright/app-copyright";
import appAssociatedLink from "../../components/page-component/app-associated-link/app-associated-link";
import appSwiper from "../../components/page-component/app-swiper/app-swiper";
import diyFormRadio from "../../components/page-component/diy-form/diy-form-radio";
import diyFormInput from "../../components/page-component/diy-form/diy-form-input";
import diyFormButton from "./diy-form-button";
import formValue from "../../components/page-component/diy-form/formValue";
import diyFormCalendar from "../../components/page-component/diy-form/diy-form-calendar";
import diyFormMenu from "../../components/page-component/diy-form/diy-form-menu";
import diyFormUimage from "../../components/page-component/diy-form/diy-form-uimage";
import diyFormUvideo from "../../components/page-component/diy-form/diy-form-uvideo";
import diyFormSwitch from "../../components/page-component/diy-form/diy-form-switch";
import diyFormAgreement from "../../components/page-component/diy-form/diy-form-agreement";
import diyCalc from "./diy-calc";
import diyNumberIn from "./diy-number-in";
import {mapGetters} from "vuex";

export default {
    name: 'goods-form',
    components: {
        appRich,
        appEmpty,
        appImageAd,
        appHotspot,
        appVideo,
        appCopyright,
        appAssociatedLink,
        appSwiper,
        diyFormRadio,
        diyFormInput,
        diyFormButton,
        diyFormCalendar,
        diyFormMenu,
        diyFormUimage,
        diyFormUvideo,
        diyFormSwitch,
        diyFormAgreement,
        diyCalc,
        diyNumberIn,
    },

    props: {
        pageId: [Number, String],
        template_message_list: Array,
        value: {
            type: Object
        }
    },
    watch: {
        formList: {
            handler(newVal) {
                this.otherForm = [];
                this.error = '';
                const ignore = [].concat(this.hideIds, this.hideIdsStatus);
                for (let formItem of newVal) {
                    if (formItem.id != 'form-goods-button' && formItem.data && formItem.data.title && formItem.id != 'link') {
                        let form = new formValue({
                            key: formItem.id,
                            label: formItem.data.title,
                            value: formItem.value || null,
                            required: formItem.data.is_required
                        });
                        form.add({unique: formItem.data.key || ''});
                        this.otherForm.push(form.getObject());
                    }
                }
                this.handlerLogicData();
            },
            immediate: true,
            deep: true
        },
    },
    onLoad(options) {
        this.$commonLoad.onload(options);

        let {date, stock, price, goods_id} = options;

        this.options = options;
        date = JSON.parse(date);

        this.$request({
            url: this.$api.goods.form_data,
            data: {
                id: goods_id,
                goods_num: options.stock,
            },
            method: 'get',
        }).then(response => {
            if (response.code === 0) {
                const {form_data, logic_data, name} = response.data.customization_data;
                uni.setNavigationBarTitle({title: name});
                this.logicData = logic_data;
                this.formList = form_data;
                this.componentShow = this.formList;
            } else {
                uni.showToast({title: response.msg, icon: 'none'});
                setTimeout(() => {
                    uni.navigateBack({delta: 1});
                }, 2000);
            }
        });

    },
    computed: {
        ...mapGetters('iPhoneX', {
            botNavHei: 'getNavHei',
        }),
        componentShow: {
            get() {
                return ({data}) => {
                    return [].concat(this.hideIds).indexOf(data.key) === -1;
                }
            },
            set(value) {
                let hideIdsStatus = [];
                for (let _ of value) {
                    if (['form-goods-button'].indexOf(_.id) !== -1) continue
                    const {has_show, key} = _.data
                    if (has_show == 0) hideIdsStatus.push(key)
                }
                this.hideIdsStatus = hideIdsStatus;
                this.hideIds = [].concat(this.hideIdsStatus);
            }
        },
        radioValue: {
            get() {
                return (column) => {
                    return this.radioArr[column.data.key];
                }
            },
            set({k, data}) {
                this.radioArr[k] = data;
            }
        },
        selectValue: {
            get() {
                return (key) => {
                    return this.selectArr[key];
                }
            },
            set({k, data}) {
                this.selectArr[k] = data;
            }
        },
    },
    data() {
        return {
            radioArr: [],
            selectArr: [],
            is_start_show: false,
            componShow: false,

            video_url: '',
            error: '',
            formList: [],
            otherForm: [],
            logicData: [],
            options: {},
            mch_id: 0,

            hideIds: [],
            hideIdsStatus: [],
            setObj: null,
            changeHide: new Set(),
        }
    },
    methods: {
        delet(hideIds){
            const ignore = [].concat(this.hideIds, this.hideIdsStatus);
            let arr = ignore.filter(_ => Array.from(hideIds).indexOf(_) !== -1);
            for (let k = 0; k < arr.length; k++) {
                let i = {
                    k: arr[k],
                }
                for (let jj in this.otherForm) {
                    let j = this.otherForm[jj];
                    if (j.unique === i.k) {
                        for (let _ in this.formList) {
                            if (this.formList[_].id === 'radio' && this.formList[_].data.key === i.k) {
                                this.formList[_].value = null
                                this.formList[_].data.list.forEach(_ => {
                                    _.value = false;
                                })
                                let ref = 'refradio' + i.k;
                                if (this.$refs[ref]) {
                                    this.$refs[ref][0].updateNewList(this.formList[_].data.list);
                                }

                            }
                            if (this.formList[_].id === 'select' && this.formList[_].data.key === i.k) {
                                console.error(i.k);
                                this.formList[_].value = [];
                                this.formList[_].data.list.forEach(_ => {
                                    _.value = false;
                                })
                                let ref = 'refselect' + i.k;
                                if (this.$refs[ref]) {
                                    this.$refs[ref][0].updateNewList(this.formList[_].data.list);
                                }
                            }
                        }
                        this.otherForm[jj].value = null;
                    }
                }
            }
        },
        testSubmit() {
            this.error = '';
            const ignore = [].concat(this.hideIds, this.hideIdsStatus);
            for (let formItem of this.formList) {
                let form = new formValue({
                    key: formItem.id,
                    label: formItem.data.title,
                    value: formItem.value || null,
                    required: formItem.data.is_required
                });

                if (formItem.data && formItem.data.key && !this.componentShow(formItem)) {
                    continue;
                }
                if (form.key === 'input' && !formItem.data.is_disabled) {
                    if (form.value && form.value.text && form.value.text.length < formItem.data.min) {
                        this.error = form.label + '最少输入' + formItem.data.min + '个字符';
                        continue;
                    }
                }
                if (form.key === 'text' && !formItem.data.is_disabled) {
                    if (form.value && form.value.length < formItem.data.min) {
                        this.error = form.label + '最少输入' + formItem.data.min + '个字符';
                        continue;
                    }
                }
                if (form.key === 'select') {
                    if (form.value && form.value.length > 0 && form.value.length < formItem.data.min) {
                        this.error = form.label + '最少选择' + formItem.data.min + '项';
                        continue;
                    }
                    if (form.value && form.value.length > 0 && form.value.length > formItem.data.max) {
                        this.error = form.label + '最多选择' + formItem.data.max + '项';
                        continue;
                    }
                }
                if (form.key === 'uvideo') {
                    if (form.value && form.value.length > 0 && form.value.length < formItem.data.min_num) {
                        this.error = form.label + '最少上传' + formItem.data.min_num + '个';
                        continue;
                    }
                    if (form.value && form.value.length > 0 && form.value.length > formItem.data.max_num) {
                        this.error = form.label + '最多上传' + formItem.data.max_num + '个';
                        continue;
                    }
                }
                if (form.key === 'uimage' && formItem.data.type === 'ordinary') {
                    if (form.value && form.value.length > 0 && form.value.length < formItem.data.min_num) {
                        this.error = form.label + '最少上传' + formItem.data.min_num + '张';
                        continue;
                    }
                    if (form.value && form.value.length > 0 && form.value.length > formItem.data.max_num) {
                        this.error = form.label + '最多上传' + formItem.data.max_num + '张';
                        continue;
                    }
                }
                if (form.required == 1) {
                    if (form.value == null) {
                        if (form.key !== 'input' && form.key !== 'text' && form.key !== 'phone') {
                            this.error = '请选择' + form.label;
                        } else {
                            this.error = '请填写' + form.label;
                        }

                    } else {
                        if (form.key === 'menu') {
                            if (formItem.data.type === 'date' && form.value) {
                                if (formItem.data.data_type && formItem.data.data_type.is_now == 1) {
                                    if (!form.value.fulldate) {
                                        this.error = '请填写' + form.label
                                    }
                                } else {
                                    if (!(form.value.alone_at || (form.value.begin_at && form.value.end_at))) {
                                        this.error = '请将' + form.label + '填写完整';
                                    }
                                }
                            }
                        } else if (form.key === 'uimage') {
                            if (formItem.data.type === 'ordinary') {
                                if (form.value && form.value.length == 0) {
                                    this.error = '请选择' + form.label;

                                }
                            } else {
                                let num = formItem.data.type === 'license' ? 1 : 2;
                                if (!form.value || form.value.filter(item => !!item).length < num) {
                                    this.error = '请将' + form.label + '填写完整';

                                }
                            }
                        } else if (form.key === 'uvideo') {
                            if (form.value && form.value.length == 0) {
                                this.error = '请选择' + form.label;

                            }
                        } else if (form.key === 'calendar') {
                            if (!(form.value.fulldate || (form.value.before && form.value.after))) {
                                this.error = '请将' + form.label + '填写完整';

                            }
                        } else if (form.key === 'agreement') {
                            if (!form.value.is_check) {
                                this.error = '请阅读并勾选' + form.label;

                            }
                        } else if (form.key === 'select') {
                            if (form.value && form.value.length == 0) {
                                this.error = '请选择' + form.label;
                            }
                        } else if (form.key === 'input') {
                            if (!form.value.text) {
                                this.error = '请填写' + form.label;
                            }
                        }
                    }
                }
            }
        },
        rubikHotspot(hotspot) {
            if (hotspot && hotspot.link) {
                hotspot.link.url = hotspot.link.value;
                hotspot.link.openType = hotspot.link.open_type;
            }
            return hotspot;
        },
        play(e) {
            this.video_url = e.video;
        },
        reset() {
            this.formList = [];
            this.$nextTick(() => {
                this.formList = JSON.parse(JSON.stringify(this.value.list))
                this.$forceUpdate();
            })
        },
        updateValue({index, value}) {
            const self = this;
            setTimeout(_ => {
                let obj = self.formList[index];
                obj.value = value;
                self.setObj = obj;
                self.formList.splice(index, 1, obj)
                self.$forceUpdate();
            }, 100)
        },

        ////////
        handlerLogicData() {
            if (this.is_start_show) return
            this.is_start_show = true

            let hideIds = new Set(this.hideIdsStatus);
            let logicData = this.logicData;

            let a  = false;
            for (let __ in logicData) {
                let _ = logicData[__], {rule_after, rule_begin} = _, sentinel = 0;

                // let isNext = true;
                // if (this.setObj) isNext = rule_begin.some(_ => _.k === this.setObj.data.key);
                // if (!isNext) continue;

                a = true;
                for (let i of rule_begin) {
                    for (let j of this.otherForm) {
                        if (j.unique === i.k && j.value) {
                            let {key, value} = j
                            switch (key) {
                                case 'menu':
                                    let {type} = value;
                                    if (type === 'date') {
                                        let {alone_at, begin_at, end_at} = value;
                                        if (alone_at && i.v === alone_at) {
                                            sentinel++;
                                        } else if (begin_at && end_at) {
                                            if (begin_at <= i.v && end_at >= i.v) {
                                                sentinel++;
                                            }
                                        }
                                    }
                                    if (type === 'store') {
                                        const {store_id} = value;
                                        let store_id_in = store_id instanceof Array ? store_id[0] : store_id;
                                        if (store_id == store_id_in && store_id_in) {
                                            sentinel++;
                                        }
                                    }
                                    if (type === 'address' || type === 'basic') {
                                        let {text} = value;
                                        text = text.split('-');

                                        if (text && JSON.stringify(text.map(_ => _.trim())) === JSON.stringify(i.v.map(_ => _.trim()))) {
                                            sentinel++;
                                        }
                                    }
                                    if (type === 'time') {
                                        let {alone_time, begin_time, end_time} = value;
                                        if (i.v instanceof Array) {
                                            if (begin_time >= i.v[0] && end_time <= i.v[1]) {
                                                sentinel++;
                                            }
                                        } else {
                                            if (i.v === alone_time) {
                                                sentinel++;
                                            }
                                        }
                                    }
                                    break;
                                case 'radio':
                                    let r_in = value, r_d_in = i.v[0]
                                    if (r_in === r_d_in) sentinel++;
                                    break;
                                case 'select':
                                    let s_in = value.sort(), s_d_in = i.v.sort();
                                    if (s_d_in[0] && s_in.find(_ => _ === s_d_in[0])) sentinel++
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    if (sentinel && sentinel === rule_begin.length) {
                        hideIds = this.playup(rule_after, hideIds);
                    }
                }
            }
            if(a){
                this.delet(hideIds);
                this.$nextTick(() => {
                    this.hideIds = Array.from(hideIds);
                    this.is_start_show = false;
                })
            } else {
                this.$nextTick(() => {
                    this.is_start_show = false;
                })
            }
            return logicData;
        },
        playup(rule_after, hideIds) {
            console.log('触发success => ', rule_after);
            for (let i of rule_after) {
                for (let jj in this.otherForm) {
                    let j = this.otherForm[jj];
                    if (j.unique === i.k) {
                        if (i.v == -1) {
                            hideIds.has(j.unique) && hideIds.delete(j.unique);
                            continue
                        }
                        if (i.v == -2) {
                            if(hideIds.has(j.unique)){
                                continue
                            }
                            if(this.hideIdsStatus.indexOf(j.unique) !== -1){
                                continue
                            }
                            for (let _ in this.formList) {
                                if (this.formList[_].id === 'radio' && this.formList[_].data.key === i.k) {
                                    this.formList[_].value = null
                                    this.formList[_].data.list.forEach(_ => {
                                        _.value = false;
                                    })
                                    let ref = 'refradio' + i.k;
                                    if (this.$refs[ref]) {
                                        this.$refs[ref][0].updateNewList(this.formList[_].data.list);
                                    }
                                }
                                if(this.formList[_].id === 'select' && this.formList[_].data.key === i.k){
                                    this.formList[_].value = [];
                                    this.formList[_].data.list.forEach(_ => {
                                        _.value = false;
                                    })
                                    let ref = 'refselect' + i.k;
                                    if (this.$refs[ref]) {
                                        this.$refs[ref][0].updateNewList(this.formList[_].data.list);
                                    }
                                }
                            }
                            this.otherForm[jj].value = null;
                            hideIds.add(j.unique);
                            continue;
                        }
                        switch (j.key) {
                            case 'select':
                                let selectValue = this.selectValue(i.k);
                                for (let _ of this.formList) {
                                    const {key, list} = _.data;
                                    if (_.id === 'select' && key === i.k && !selectValue) {
                                        selectValue = list;
                                        this.setObj = _;
                                        break;
                                    }
                                }
                                if (selectValue && selectValue.length) {
                                    let value = [];
                                    selectValue = selectValue.map((_, index) => {
                                        if (_.label === i.v || (j.value && j.value.indexOf(_.label) !== -1)) _.value = true;
                                        if (_.value) {
                                            value.push(_.label)
                                        }
                                        return _;
                                    })
                                    this.otherForm[jj].value = value;
                                    // this.selectValue = {k: i.k, data: selectValue};
                                    let ref = 'refselect' + i.k;
                                    if (this.$refs[ref]) {
                                        this.$refs[ref][0].updateNewList(selectValue);
                                    }
                                }
                                break;
                            case 'radio':
                                let radioValue = [];
                                for (let _ of this.formList) {
                                    const {key, list} = _.data;
                                    if (_.id === 'radio' && key === i.k) {
                                        radioValue = list;
                                        this.setObj = _;
                                        break;
                                    }
                                }
                                if (radioValue && radioValue.length) {
                                    radioValue = radioValue.map(_ => {
                                        _.value = _.label === i.v;
                                        if (_.value) {
                                            this.otherForm[jj].value = _.label;
                                        }
                                        return _;
                                    })
                                    let ref = 'refradio' + i.k;
                                    if (this.$refs[ref]) {
                                        this.$refs[ref][0].updateNewList(radioValue);
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            return hideIds;
        },
    },
    provide() {
        return {goodsForm: this}
    }
}
</script>

<style lang="scss" scoped>
.dialog {
    position: fixed;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, .3);
    width: 100%;
    height: 100%;
    z-index: 100;
}
</style>
